package com.loser.gateway.broadcast;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.loser.gateway.biz.OnlineHandler;
import com.loser.gateway.utils.ChannelUtils;
import com.loser.gateway.utils.CmdUtils;
import com.loser.module.base.proto.base.InnerResponse;
import com.loser.module.base.proto.broadcast.BroadCastMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Component
public class BroadCastHandler {


    @Autowired
    private OnlineHandler onlineHandler;

    public void sendBroadCast(BroadCastMsg msg) {

        if (Objects.isNull(msg) || StringUtils.isEmpty(msg.getTraceId())) {
            return;
        }
        doSendBroadCast(msg);

    }

    private void doSendBroadCast(BroadCastMsg msg) {

        Map<String, Channel> channelMap = onlineHandler.getBroadcastChannels(msg);
        if (MapUtil.isEmpty(channelMap)) {
            return;
        }
        byte[] bytes = msg.getMessage();
        ByteBuf buf = CmdUtils.merge(msg.getTypeCmd(), bytes);
        for (Channel channel : channelMap.values()) {
            channel.writeAndFlush(buf);
        }

    }

}
